package com.sdgakj.utils;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.InputSource;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Files;

@Component
public class MyUtils {

    public static final String imagePath = PropUtil.getInstance().get("upload.image.path");
    public static final String APPID = "wx69916bbadca66990";
    public static final String APPSECRET = "ec972f2cf6ba0461cfc4f9e85c59a5ab";

    /**
     * 写入本地文件
     * 
     * @param file
     * @param path
     * @return
     */
    public static String writeFile(MultipartFile file, String type, Long id) {
        String fileName = file.getOriginalFilename();
        UUID uuid = UUID.randomUUID();
        String picName = uuid + fileName.substring(fileName.lastIndexOf("."));
        String picdir = imagePath + "temp/" + type + "/" + id + "/";
        String picPathName = type + "/" + id + "/" + picName;
        final File filePath = new File(picdir);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        String picpath = imagePath + "temp/" + type + "/" + id + "/" + picName;
        final File newFile = new File(picpath);
        try {
            Files.write(file.getBytes(), newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return picPathName;
    }

    public static void imageCut(Long id, String imageFile, String x, String y, String width, String height) {
        FileInputStream is = null;
        ImageInputStream iis = null;
        String imageType = imageFile.substring(imageFile.lastIndexOf(".") + 1);

        String srcPath = imagePath + "temp/" + imageFile;
        String outPath = imagePath + "my/" + imageFile;
        String realOutPath = outPath.substring(0, outPath.lastIndexOf("/") + 1) + id + "." + imageType;
        File outPathDir = new File(outPath.substring(0, outPath.lastIndexOf("/")));
        if (!outPathDir.exists()) {
            outPathDir.mkdirs();
        }
        File newFile = new File(realOutPath);
        if (newFile.isFile() && newFile.exists()) {
            newFile.delete();
        }
        try {
            is = new FileInputStream(srcPath);
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(imageType);
            ImageReader reader = it.next();
            iis = ImageIO.createImageInputStream(is);
            reader.setInput(iis, true);
            ImageReadParam param = reader.getDefaultReadParam();
            if (x.indexOf(".") > -1) {
                x = x.substring(0, x.indexOf("."));
            }
            if (y.indexOf(".") > -1) {
                y = y.substring(0, y.indexOf("."));
            }
            if (width.indexOf(".") > -1) {
                width = width.substring(0, width.indexOf("."));
            }
            if (height.indexOf(".") > -1) {
                height = height.substring(0, height.indexOf("."));
            }

            Rectangle rect = new Rectangle(Integer.valueOf(x), Integer.valueOf(y), Integer.valueOf(width),
                    Integer.valueOf(height));
            param.setSourceRegion(rect);
            BufferedImage bi = reader.read(0, param);
            ImageIO.write(bi, imageType, new File(realOutPath));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (iis != null)
                try {
                    iis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    public static void compressPic(String imageFile) {
        CompressPic compressPic = new CompressPic();
        String inputDir = imagePath + "my/" + imageFile.substring(0, imageFile.lastIndexOf("/") + 1);
        String outputDir = imagePath + "my/" + imageFile.substring(0, imageFile.lastIndexOf("/") + 1);
        String fileName = imageFile.substring(imageFile.lastIndexOf("/") + 1);
        compressPic.compressPic(inputDir, outputDir, fileName, fileName);
    }

    public static String getUrlData(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse httpReponse = null;
        try {
            httpReponse = httpClient.execute(httpget);
            HttpEntity entity = httpReponse.getEntity();
            // 返回内容
            return EntityUtils.toString(entity);
        } catch (Exception e) {

        } finally {
            try {
                if (null != httpReponse) {
                    httpReponse.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "";
    }

    public static Map<String, Object> parseJson(String json) {
        Map<String, Object> dataMap = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            dataMap = objectMapper.readValue(json, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataMap;
    }

    public static Map<String, String> parseXml(String xmlStr) {
        Map<String, String> resultMap = new HashMap<String, String>();
        try {
            StringReader sr = new StringReader(xmlStr);
            InputSource is = new InputSource(sr);

            SAXReader reader = new SAXReader();
            Document document = reader.read(is);
            Element root = document.getRootElement();
            for (Object obj : root.elements()) {
                Element element = (Element) obj;
                resultMap.put(element.getName(), element.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;

    }

    public static void main(String[] args) {
        // String code = "001aafffaccb0c31621fde9b6894166a";
        // String urlFormat =
        // "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        // String url = String.format(urlFormat, APPID, APPSECRET, code);
        // System.out.println(getUrlData(url));

        // String xmlStr =
        // "<xml><ToUserName><![CDATA[gh_e4c9bb552bd2]]></ToUserName><FromUserName><![CDATA[onq8QuM_wYrHZ0N5JKwym7jV_ZKA]]></FromUserName><CreateTime>1419523116</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[1]]></Content><MsgId>6096805359338338455</MsgId></xml>";
        // System.out.println(parseXml(xmlStr));

        String lbsUrlFormat = "http://api.map.baidu.com/geosearch/v3/nearby?ak=WqtBXK9Vm1p0sGvr48h8rpO0&geotable_id=85323&location=%s,%s&radius=30000000&sortby=distance:1";
        String latitude = "116.218361";
        String longitude = "39.905430";
        String lbsUrl = String.format(lbsUrlFormat, latitude, longitude);
        // System.out.println(getUrlData(lbsUrl));

        Map<String, Object> dataMap = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            dataMap = objectMapper.readValue(getUrlData(lbsUrl), Map.class);
            List<Map<String, Object>> locals = (List<Map<String, Object>>) dataMap.get("contents");
            for (Map<String, Object> local : locals) {
                System.out.println(
                        String.format("userid:[%s], distance:[%s]", local.get("userid"), local.get("distance")));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Integer getAge(String IDCardNum) {
        Calendar cal1 = Calendar.getInstance();
        Calendar today = Calendar.getInstance();
        System.out.println(IDCardNum.substring(12, 14));
        cal1.set(Integer.parseInt(IDCardNum.substring(6, 10)), Integer.parseInt(IDCardNum.substring(10, 12)),
                Integer.parseInt(IDCardNum.substring(12, 14)));
        return getYearDiff(today, cal1);
    }

    public static int getYearDiff(Calendar cal, Calendar cal1) {
        int m = (cal.get(cal.MONTH)) - (cal1.get(cal1.MONTH));
        int y = (cal.get(cal.YEAR)) - (cal1.get(cal1.YEAR));
        return (y * 12 + m) / 12;
    }
    
    public static boolean isPropertyByClass(Class<?> c, String name) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            if(field.getName().equals(name)) {
                return true;
            }
        }
        return false;
    }
    
    
    public static Boolean imageCut(String imageFile, String x, String y, String width, String height) {
        FileInputStream is = null;
        ImageInputStream iis = null;
        String imageType = imageFile.substring(imageFile.lastIndexOf(".") + 1);
        
        String srcPath = imagePath + "temp/" + imageFile;
        String outPath = imagePath + "my/" + imageFile;
        File outPathDir = new File(outPath.substring(0, outPath.lastIndexOf("/")));
        if (!outPathDir.exists()) {
            outPathDir.mkdirs();
        }
        File newFile = new File(outPath);
        if (newFile.isFile() && newFile.exists()) {
            newFile.delete();
        }
        try {
            is = new FileInputStream(srcPath);
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(imageType);
            ImageReader reader = it.next();
            iis = ImageIO.createImageInputStream(is);
            reader.setInput(iis, true);
            ImageReadParam param = reader.getDefaultReadParam();
            if (x.indexOf(".") > -1) {
                x = x.substring(0, x.indexOf("."));
            }
            if (y.indexOf(".") > -1) {
                y = y.substring(0, y.indexOf("."));
            }
            if (width.indexOf(".") > -1) {
                width = width.substring(0, width.indexOf("."));
            }
            if (height.indexOf(".") > -1) {
                height = height.substring(0, height.indexOf("."));
            }

            Rectangle rect = new Rectangle(Integer.valueOf(x), Integer.valueOf(y), Integer.valueOf(width),
                    Integer.valueOf(height));
            param.setSourceRegion(rect);
            BufferedImage bi = reader.read(0, param);
            ImageIO.write(bi, imageType, new File(outPath));
        }catch(IIOException iioe) {
            return false;
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (iis != null)
            try {
                iis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
    
    
    public static void compressPicByWidthAndHeight(String imageFile, int width, int height) {
        CompressPic compressPic = new CompressPic();
        compressPic.setWidthAndHeight(width, height);
        String inputDir = imagePath + "my/" + imageFile.substring(0, imageFile.lastIndexOf("/") + 1);
        String outputDir = imagePath + "my/" + imageFile.substring(0, imageFile.lastIndexOf("/") + 1);
        String fileName = imageFile.substring(imageFile.lastIndexOf("/") + 1);
        compressPic.compressPic(inputDir, outputDir, fileName, fileName);
    }

    public static String StringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        // String regEx = "[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx = "[`@#$%^&*+=|@#￥《》`%*——+—_~|【】……；‘”“’]·";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    // unicode转化汉字
    public static StringBuffer decodeUnicode(final String dataStr) {
        final StringBuffer buffer = new StringBuffer();
        String tempStr = "";
        String operStr = dataStr;
        if (operStr != null && operStr.indexOf("\\u") == -1)
            return buffer.append(operStr);
        if (operStr != null && !operStr.equals("") && !operStr.startsWith("\\u")) {
            tempStr = operStr.substring(0, operStr.indexOf("\\u"));
            operStr = operStr.substring(operStr.indexOf("\\u"), operStr.length());// operStr字符一定是以unicode编码字符打头的字符串
        }
        buffer.append(tempStr);
        // 循环处理,处理对象一定是以unicode编码字符打头的字符串
        while (operStr != null && !operStr.equals("") && operStr.startsWith("\\u")) {
            tempStr = operStr.substring(0, 6);
            operStr = operStr.substring(6, operStr.length());
            String charStr = "";
            charStr = tempStr.substring(2, tempStr.length());
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            if (operStr.indexOf("\\u") == -1) {
                buffer.append(operStr);
            } else { // 处理operStr使其打头字符为unicode字符
                tempStr = operStr.substring(0, operStr.indexOf("\\u"));
                operStr = operStr.substring(operStr.indexOf("\\u"), operStr.length());
                buffer.append(tempStr);
            }
        }
        return buffer;
    }

    public static String get12RandomNum() {
        StringBuffer sb = new StringBuffer();
        for (int j = 0; j < 4; j++) {
            sb.append(new Random().nextInt(10));
        }
        for (int j = 0; j < 4; j++) {
            sb.append(new Random().nextInt(10));
        }
        for (int j = 0; j < 4; j++) {
            sb.append(new Random().nextInt(10));
        }
        return sb.toString();
    }
    
    /**验证手机号格式是否正确*/
    public static boolean checkMobile(String mobile){
       Pattern p = null;  
	    Matcher m = null;  	
	    boolean b = false;   
	    p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号  
	    m = p.matcher(mobile);  
	    b = m.matches();   
	    return b;
   }
}
